/*
 * @Author: lizuoxian
 * @Date: 2023-03-10 16:48:10
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-15 18:00:44
 * @FilePath: /wx-app-h5/src/router/index.js
 * @Description:
 */
import Vue from 'vue'
import Router from 'vue-router'
import Routes from './routes.js'
Vue.use(Router)
let appRouter = new Router({
  base: import.meta.env.VITE_ROUTER_BASW,
  mode: 'history',
  routes: Routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})
appRouter.beforeEach((to, from, next) => {
  const title = to.meta.title
  document.title = title
  next()
})

appRouter.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = appRouter.history.pending.fullPath
  if (isChunkLoadFailed) {
    appRouter.replace(targetPath)
  }
})

// 解决 vue-router 3，重新进入相同路由时报错的问题 Uncaught(in Promise)
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push(toLocation) {
  return VueRouterPush.call(this, toLocation).catch((err) => err)
}

export default appRouter
